<?php
/*
 * Create a session for a user by verifying supplied username and password.
 */

// check that we have the necessary parameters
if (!F3::exists('POST.email') || !F3::exists('POST.password'))
{
  // we need at least email and password
  header('HTTP/1.1 403');
  header("Content-Type: application/json");
  $err = array("error_message" => "Authentication failed.");
  echo json_encode($err);
  return;
}

// authenticate user
$param = array('1' => F3::get('POST.email'));
$res = DB::sql("SELECT id, email, nickname, password FROM user WHERE email=?", $param);
if (count($res) == 0)
{
  // could not find user
  header('HTTP/1.1 403');
  header("Content-Type: application/json");
  $err = array("error_message" => "Authentication failed.");
  echo json_encode($err);
  return;
}

// get password hash
$row = $res[0];
$id = $row['id'];
$email = $row['email'];
$nickname = $row['nickname'];
$hash = $row['password'];

// get hasher
// base-2 logarithm of the iteration count used for password stretching
$hash_cost_log2 = 8;
// make hashes non-portable to older systems
$hash_portable = FALSE;
// get hasher
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);

// check password
if (!$hasher->CheckPassword(F3::get('POST.password'), $hash)) {
  // password does not match
  header('HTTP/1.1 403');
  header("Content-Type: application/json");
  $err = array("error_message" => "Authentication failed.");
  echo json_encode($err);
  return;
}

$param = array('1' => $id);
$admin = DB::sql("SELECT id from admin WHERE id=?", $param);
if(count($admin)>0):
	$admin = 1;
else:
	$admin = 0;
endif;

// authentication succeeded
// set session
F3::set('SESSION.user_id', $id);
F3::set('SESSION.user_email', $email);
F3::set('SESSION.nickname', $nickname);
if($admin==1)
	F3::set('SESSION.admin', $admin);

header('HTTP/1.1 201');
header("Content-Type: application/json");
echo json_encode(array("success" => "1", "user_id" => $_SESSION['user_id'], "user_email" => $email, "admin" => $admin));

?>
